package com.antis.olsl.magic.outbound.number;

import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.antis.olsl.arouterlib.MagicRoutePath;
import com.antis.olsl.base.BaseActivity;
import com.antis.olsl.library.dialog.ChooseDateDialog;
import com.antis.olsl.library.dialog.ChooseWarehouseDialog;
import com.antis.olsl.library.response.SalesroomOrWarehouseInfo;
import com.antis.olsl.base.utils.ToastUtil;
import com.antis.olsl.library.widget.ChooseWarehouseView;
import com.antis.olsl.library.widget.MyInputSearchLayout;
import com.antis.olsl.magic.R;
import com.antis.olsl.magic.adapter.OutboundListAdapter;
import com.antis.olsl.magic.databinding.ActivityOutboundNumberBinding;
import com.antis.olsl.magic.outbound.OutboundContract;
import com.antis.olsl.magic.outbound.OutboundPresenter;
import com.antis.olsl.magic.response.GetExWarehouseTopListResp;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.trello.rxlifecycle2.LifecycleTransformer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import timber.log.Timber;

/**
 * 出库数量
 *
 * @author hhh
 */
@Route(path = MagicRoutePath.ACTIVITY_OUTBOUND_NUMBER)
public class OutboundNumberActivity extends BaseActivity<ActivityOutboundNumberBinding> implements ChooseWarehouseView.ChooseWarehouseListener,
        ChooseWarehouseDialog.ChooseWarehouseListener, OutboundContract.View, ChooseDateDialog.ChooseDateListener,
        MyInputSearchLayout.TextChangedListener {

    private ChooseWarehouseDialog mDialog;
    private String salesRoomIds = "";
    private SalesroomOrWarehouseInfo mInfo;
    private ArrayList<SalesroomOrWarehouseInfo> salesroomInfos = new ArrayList<>();
    private ArrayList<SalesroomOrWarehouseInfo> selectedSalesroomInfos = new ArrayList<>();

    private OutboundPresenter mPresenter;

    private SimpleDateFormat textDateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());

    private ChooseDateDialog chooseDateDialog;
    private Date startDate;
    private Date endDate;

    private List<GetExWarehouseTopListResp.ContentBean> mList = new ArrayList<>();
    private OutboundListAdapter mAdapter;

    private String searchText;
    private int pageNum = 1;
    private boolean isEnd;

    @Override
    protected ActivityOutboundNumberBinding getViewBinding() {
        return ActivityOutboundNumberBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @Override
    protected void initPresenter() {
        super.initPresenter();
        mPresenter = new OutboundPresenter();
        mPresenter.takeView(this);
    }

    @Override
    protected void initViews() {
        viewBinding.layoutChooseWarehouse.chooseWarehouseView.setWarehouseInfos(null);
        viewBinding.layoutChooseWarehouse.chooseWarehouseView.setChooseWarehouseListener(this);

        viewBinding.layoutSearchInput.myInputSearchLayout.setHintText("请输入商品编码/名称");
        viewBinding.layoutSearchInput.myInputSearchLayout.setListener(this);

        initDate();

        mAdapter = new OutboundListAdapter(R.layout.item_outbound_list, mList);
        viewBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        viewBinding.recyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                GetExWarehouseTopListResp.ContentBean bean = mList.get(position);
                if (null != bean) {
                    ARouter.getInstance().build(MagicRoutePath.ACTIVITY_OUTBOUND_DETAIL)
                            .withSerializable("bean", bean)
                            .withInt("type", 0)
                            .navigation();
                }
            }
        });

//        mAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore() {
//                mRecyclerView.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (isEnd) {
//                            mAdapter.getLoadMoreModule().loadMoreEnd();
//                        } else {
//                            loadData();
//                        }
//                    }
//                }, 200);
//            }
//        });

        viewBinding.rlChooseDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseDateDialog = new ChooseDateDialog(OutboundNumberActivity.this, "选择时间", startDate, OutboundNumberActivity.this, "startDate");
            }
        });
    }

    @Override
    protected void initData() throws IllegalAccessException {

    }

    private void initDate() {
        Calendar calendar = Calendar.getInstance();

        endDate = new Date();
        calendar.setTime(endDate);
        //初始进来查询近7天的数据
        calendar.add(Calendar.DATE, -7);
        startDate = calendar.getTime();
        setDateText();

        loadData();
    }

    private void setDateText() {
        String date = textDateFormat.format(startDate) + "-" + textDateFormat.format(endDate);
        viewBinding.tvDate.setText(date);
    }

    private void loadData() {
        flushData();
    }

    private void flushData() {
        HashMap<String, Object> map = new HashMap<>(7);
        map.put("topType", 1);
        map.put("houseId", salesRoomIds);
        map.put("startTime", dateFormat.format(startDate));
        map.put("endTime", dateFormat.format(endDate));
        map.put("keyword", searchText);
        map.put("pageNum", pageNum);
        map.put("pageSize", 10);
        mPresenter.getExWarehouseTopList(map);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mPresenter) {
            mPresenter.unSubscribe();
        }
        if (null != mDialog) {
            mDialog.dismiss();
        }
    }

    @Override
    public void clickChooseListener() {
        if (salesroomInfos == null || salesroomInfos.size() == 0) {
            getWareList();
        } else {
            mDialog = new ChooseWarehouseDialog(this, 0, salesroomInfos, OutboundNumberActivity.this);
        }
    }

    private void getWareList() {
        HashMap<String, Object> map = new HashMap<>();
        mPresenter.getWarehouseInfoList(map);
    }

    @Override
    public void clickPhone(String phone) {

    }

    @Override
    public void onChooseWarehouseListener(boolean isChooseAll, ArrayList<SalesroomOrWarehouseInfo> choosedFiledInfos, ArrayList<SalesroomOrWarehouseInfo> sourceInofs, int selectedIndex) {
        salesroomInfos = sourceInofs;
        selectedSalesroomInfos = choosedFiledInfos;
        if (selectedIndex == -1) {
            salesRoomIds = "";
            viewBinding.layoutChooseWarehouse.chooseWarehouseView.setWarehouseInfos(null);
        } else {
            salesRoomIds = filterIds();
        }
        flushData();
    }

    private String filterIds() {
        ArrayList<SalesroomOrWarehouseInfo> infos = salesroomInfos;
        String name = "";
        String ids = "";
        for (int i = 0; i < infos.size(); i++) {
            ids += TextUtils.isEmpty(ids) ? infos.get(i).getId() : "," + infos.get(i).getId();
            name += TextUtils.isEmpty(name) ? infos.get(i).getName() : "," + infos.get(i).getName();
        }

        if (infos.size() > 0) {
            mInfo = infos.get(0);
        }
        viewBinding.layoutChooseWarehouse.chooseWarehouseView.setWarehouseInfos(infos);
        return ids;
    }

    @Override
    public void getWarehouseInfoListSuccess(List<SalesroomOrWarehouseInfo> list) {
        salesroomInfos.clear();
        salesroomInfos.addAll(list);
        mDialog = new ChooseWarehouseDialog(this, 0, salesroomInfos, OutboundNumberActivity.this);
    }

    @Override
    public void getWarehouseInfoListFailure(String msg) {
        Timber.tag("hhh").e("getWarehouseInfoListFailure msg= " + msg);
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(this, msg);
    }

    @Override
    public void getExWarehouseTopListSuccess(List<GetExWarehouseTopListResp.ContentBean> list) {
        if (pageNum == 1) {
            mList.clear();
        }

        mList.addAll(list);
        if (list.size() > 10) {
            isEnd = false;
            pageNum += 1;
        } else {
            isEnd = true;
        }
        mAdapter.setList(mList);
        mAdapter.getLoadMoreModule().loadMoreComplete();
    }

    @Override
    public void getExWarehouseTopListFailure(String msg) {

    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.bindToLifecycle();
    }

    @Override
    public void getDateListener(String tag, int year, int quarter, int month, int week, int day) {
        Date tmpDate = new Date();
        try {
            tmpDate = simpleDateFormat.parse(year + "-" + month + "-" + day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (tmpDate.getTime() - System.currentTimeMillis() > 0) {
            ToastUtil.showToast(this, "选择时间不能超过当前时间");
            return;
        }
        if ("startDate".equals(tag)) {
            startDate = tmpDate;
            chooseDateDialog.dismiss();
            chooseDateDialog = new ChooseDateDialog(this, "选择结束时间", endDate, this, "endDate");
        } else {
            if (tmpDate.getTime() - startDate.getTime() < 0) {
                ToastUtil.showToast(this, "结束时间必须大于开始时间");
                return;
            }
            endDate = tmpDate;
            chooseDateDialog.dismiss();
            flushData();
        }
        setDateText();
    }

    @Override
    public void onTextChangeListener(String text) {
        pageNum = 1;
        searchText = text;
        flushData();
    }
}